//
//  THFlipImageView.m
//  MengLiao
//
//  Created by xiuxin on 2022/7/15.
//  Copyright © 2022 BaseBusiness. All rights reserved.
//

#import "THFlipImageView.h"
@interface THFlipImageView()

@property (strong,nonatomic) UIView * fromView;

@property (strong,nonatomic) UIView * toView;

@property (weak,nonatomic) UIGestureRecognizer * clickGesture;

@property (strong,nonatomic) NSInvocation * trigger;

@property (nonatomic) BOOL animating;

@property (nonatomic) NSTimer * timer;

@property (nonatomic) NSInteger runCount;   //动画已经执行的次数

@end
@implementation THFlipImageView

- (instancetype)initWithFromImage:(UIImage *)fromImage toImage:(UIImage *)toImage size:(CGSize)size
{
    return [self initWithFromView:[[UIImageView alloc] initWithImage:fromImage] toView:[[UIImageView alloc] initWithImage:toImage] size:size];
}

- (instancetype)initWithFromView:(UIView *)fromView toView:(UIView *)toView size:(CGSize)size
{
    if (self = [super initWithFrame:CGRectMake(0, 0, size.width, size.height)])
    {
        _flipDirection = UIViewAnimationOptionTransitionFlipFromLeft;
        _flipDuration = 1;
        _flipInterval = 2;
        _runCount = 0;
        _repeatCount = 0;
        _touchSize = CGSizeMake(size.width + 20.0f, size.height + 20.0f);
        self.fromView = fromView;
        self.toView = toView;
        [self createUI];
        [self createViewLayouts];
    }
    return self;
}

- (void)createUI
{
    [self addSubview:_fromView];
}

- (void)createViewLayouts
{
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(self.size));
    }];
    self.fromView.frame = self.bounds;
}

- (void)willMoveToWindow:(UIWindow *)newWindow
{
    if (newWindow)
    {
        if (!_animating)
        {
            @weakify(self)
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                @strongify(self);
                [self startAnimation];
            });
        }
    }
    else
    {
        [self stopAnimation];
    }
}

- (void)addTarget:(id)target selector:(SEL)selector
{
    self.userInteractionEnabled = YES;
    self.fromView.userInteractionEnabled = NO;
    self.toView.userInteractionEnabled = NO;
    [self addClickGesture];
    _trigger = [NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]];
    [_trigger setTarget:target];
    [_trigger setSelector:selector];
    if ([_trigger.methodSignature numberOfArguments] > 2)
    {
        NSObject * view = self;
        [_trigger setArgument:&view atIndex:2];
    }
}

- (void)setDidClickBlock:(void (^)(void))didClickBlock
{
    self.userInteractionEnabled = YES;
    self.fromView.userInteractionEnabled = NO;
    self.toView.userInteractionEnabled = NO;
    [self addClickGesture];
    _didClickBlock = didClickBlock;
}

- (void)addClickGesture
{
    if (_clickGesture != nil)
    {
        [self removeGestureRecognizer:self.clickGesture];
    }
    UIGestureRecognizer * gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didClick)];
    [self addGestureRecognizer:gesture];
    self.clickGesture = gesture;
}

- (void)didClick
{
    [_trigger invoke];
    KExecuteBlock(self.didClickBlock);
}

- (void)startAnimation
{
    if (!_animating)
    {
        _animating = YES;
        [self flipAnimation];
    }
}

- (void)flipAnimation
{
    ///两次翻转算一次动画
    if (self.repeatCount > 0 && self.runCount/2 >= self.repeatCount)
    {
        [self stopAnimation];
    }
    
    if (_animating)
    {
        self.toView.frame = self.bounds;
        [self insertSubview:self.toView atIndex:0];
        [UIView transitionFromView:self.fromView toView:self.toView duration:self.flipDuration options:self.flipDirection completion:^(BOOL finished) {
            [self.fromView removeFromSuperview];
            UIView * lastFromView = self.fromView;
            self.fromView = self.toView;
            self.toView = lastFromView;
            if (_animating)
            {
                [self beginTimer];
            }
            self.runCount ++;
        }];
    }
}

- (void)beginTimer
{
    NSTimer * timer = [NSTimer timerWithTimeInterval:self.flipInterval target:self selector:@selector(flipAnimation) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.timer = timer;
}

- (void)stopAnimation
{
    if (self.runCount%2 != 0) {
        UIView * lastFromView = self.fromView;
        self.fromView = self.toView;
        self.toView = lastFromView;
        if (self.toView.superview) {
            [self.toView removeFromSuperview];
        }
        if (!self.fromView.superview) {
            [self addSubview:self.fromView];
        }
    }
    
    self.runCount = 0;
    _animating = NO;
    [self.timer invalidate];
    self.timer = nil;
}

- (void)willMoveToSuperview:(UIView *)newSuperview
{
    if (newSuperview == nil)
    {
        [self stopAnimation];
    }
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    CGFloat originX = (self.size.width - self.touchSize.width) / 2.0f;
    CGFloat originY = (self.size.height - self.touchSize.height) / 2.0f;
    CGRect extFrame = CGRectMake(originX, originY, self.touchSize.width, self.touchSize.height);
    return CGRectContainsPoint(extFrame, point);
}

@end
